package com.streaminggbs.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@Slf4j
@MapperScan(basePackages = ReadDataSourcesConfig.PACKAGES,sqlSessionFactoryRef = "readSqlSessionFactory")
public class ReadDataSourcesConfig {
    static final String PACKAGES="com.streaminggbs.mapper.read";
    private  static final String MAPPER_LOCAL ="classpath:mapper/read/*.xml";

    /** 配置读库
     * @return  DruidDataSource
     */
    @Bean(name = "readDataSource")
    @ConfigurationProperties(prefix = "read.datasource")
    public DruidDataSource readDruidDataSource(){
        return new DruidDataSource();
    }


    @Bean(name = "readSqlSessionFactory")
    public SqlSessionFactory readSqlSessionFactory(){
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(readDruidDataSource());

        try {
            sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            log.error("配置读库的SqlSessionFactory失败，error:{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Bean(name = "readTransactionManager")
    public DataSourceTransactionManager readTransactionManager(){
        return new DataSourceTransactionManager(readDruidDataSource());
    }

}
